package com.huifer.wgx.service.impl;

import com.huifer.wgx.exception.FileStorageException;
import com.huifer.wgx.exception.WgxFileNotFoundException;
import com.huifer.wgx.model.FileEntity;
import com.huifer.wgx.model.PersonnelEntity;
import com.huifer.wgx.model.WorkEntity;
import com.huifer.wgx.repository.FileRepository;
import com.huifer.wgx.repository.PersonnelRepository;
import com.huifer.wgx.repository.WorkRepository;
import com.huifer.wgx.service.FileStorageInterface;
import com.huifer.wgx.spec.CommonSpec;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>Title : FileStorageInterfaceImpl </p>
 * <p>Description : </p>
 *
 * @author huifer
 * @date 2019-03-20
 */
@Service
public class FileStorageInterfaceImpl implements FileStorageInterface {

    @Autowired
    private FileRepository fileRepository;
    @Value("${upload.path}")
    private String path;

    @Autowired
    private WorkRepository workRepository;

    @Autowired
    private PersonnelRepository personnelRepository;

    private String mkdir(Long workId, Long personnelId) {
        WorkEntity work1 = workRepository.findById(workId).get();
        PersonnelEntity p1 = personnelRepository.findById(personnelId).get();
        String upPath =
                path + work1.getWorkName() + "-" + p1.getPersonnelName()
                        + "-" + UUID.randomUUID()+"-";
        return upPath;
    }

    /**
     * 存储文件
     *
     * @param file 文件
     * @param workId 工程id
     * @param personnelId 上传id
     * @return 文件
     */
    @Override
    public FileEntity storeFile(MultipartFile file, Long workId, Long personnelId) {

        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        if (file.isEmpty()) {
            throw new FileStorageException(
                    "文件isEmpty " + fileName + ".请重试!");
        }

        try {
            if (fileName.contains("..")) {
                throw new FileStorageException("文件名有非法字符" + fileName);
            }
            // 储存到本地文件夹中
            InputStream inputStream = file.getInputStream();
            String mkdir = mkdir(workId, personnelId);

            Files.copy(inputStream, Paths.get(mkdir + fileName),
                    StandardCopyOption.REPLACE_EXISTING);
            // 储存到数据库中
            FileEntity fileEntity = new FileEntity();
            fileEntity.setFileName(fileName);
            fileEntity.setFileType(file.getContentType());
            fileEntity.setFileData(file.getBytes());
            fileEntity.setPersonnelId(personnelId);
            fileEntity.setWorkId(workId);
            fileEntity.setcPath(mkdir + fileName);
            return fileRepository.save(fileEntity);
        } catch (IOException e) {
            throw new FileStorageException(
                    "文件储存失败 " + fileName + ".请重试!", e);
        }

    }

    /**
     * 获取文件
     *
     * @param fileId 文件id
     * @return 文件
     */
    @Override
    public FileEntity getFile(Long fileId) {
        return fileRepository.findById(fileId)
                .orElseThrow(() -> new WgxFileNotFoundException("文件id未找到：" + fileId));
    }
}
